import {observable,toJS} from 'mobx';
import { getColumns, getFields, getColumnsSet } from '../data/TemplateManage';
import indexApis from '../../apis';
import * as tableApis from '../../apis/table';
import { WeaForm } from 'comsMobx';
import {message,Modal} from 'antd';
import {action } from "mobx";
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

export default class TemplateManageStore{
    id='';
    @observable loading=false;
    customid:string='';
    sourcetype:string='';//2普通查询
    @observable columns:any= [];
    templateListDataKey: string = "";
    @observable templateListDatas: any;
    @observable templateName: string = "";
    @observable templateName1: string = "";
    @observable fields: any[];
    @observable form = new WeaForm();
    @observable visible:boolean=false;
    @observable visible_set:boolean=false;
    @observable visible_set_condition:boolean=false;
    @observable pagination={
        pageSize:10,
        current:1,
        total:0,
        onChange:(current, pageSize) => {
            this.pagination.current = current;
            this.pagination.pageSize = pageSize;
        }
    }
    columnsSet: any[] = [];
    @observable DatasSet: any[] = [];
    @observable conditionForm=new WeaForm();
    @observable conditionInfo: any = [];
    @observable iconInfo = {
        icon: "icon-coms-ModelingEngine",
        iconColor: "#fff",
        iconBg: "#96358a"
      }

    init=()=>{
        this.columns=getColumns(this);
        this.columnsSet=getColumnsSet(this.checkAll);
        this.fields=getFields();
        this.form.initFormFields([{ items: this.fields.slice() }]);
        this.getTemplateListDataKey({customid:this.customid,sourcetype:this.sourcetype});
        this.getIconInfo(this.customid);
    }

    @action
    validateForm = (fields, form) => {
        for (let i = 0; i < fields.length; i++) {
            let text = fields[i].domkey[0];
            if (!fields[i].hide && fields[i].viewAttr == 3 && form.getFormParams()[text].trim() == '') {
                message.warn(getLabel(23073,"请填写")+fields[i].label+'!');
                return false;
            }
        }
        return true;
    }

    @action
    getTemplateListDataKey=(param)=>{
        indexApis.getTemplateList(param).then(action(({ status, errorCode, error, datas }) => {
            if (status == '1') {
                this.templateListDataKey = datas;
                this.getTemplateListCount();
            } else {
                message.error(`[${getLabel(127353,"错误")+errorCode}]:${error}`);
            }
            this.loading = false;
        }));
    }

    @action
    getTemplateListCount = () => {
        this.loading = true;
        tableApis.getTableCounts({ dataKey: this.templateListDataKey }).then(action(({ status, errorCode, error, count }) => {
            if (status == '1') {
                this.pagination.total = count;
                this.pagination.current=1;
                this.getTemplateListData();
            } else {
                message.error(`[${getLabel(127353,"错误")+errorCode}]:${error}`);
            }
            this.loading = false;
        }));
    }

    @action
    getTemplateListData = () => {
        this.loading = true;
        tableApis.getTableDatas({ ...this.pagination, dataKey: this.templateListDataKey }).then(action(({ status, errorCode, error, datas }) => {
            if (status == '1') {
                this.templateListDatas = datas;
            } else {
                message.error(`[${getLabel(127353,"错误")+errorCode}]:${error}`);
            }
            this.loading = false;
        }));
    }

    @action
    searchByName=(name='')=>{
        this.templateName = name;
        this.templateName1 = this.templateName;
        this.getTemplateListDataKey({customid:this.customid,templatename:name,sourcetype:this.sourcetype});
    }
    @action
    add=()=>{
        this.form.resetForm();
        this.form.updateFields({templatetype:'0'}, true);
        this.visible=true;
    }

    @action
    rightClick=(key)=>{
        if(key=='add'){
            this.add();
        }
    }

    @action
    save=()=>{
        // if (!this.validateForm(this.fields,this.form))return;
        this.form.validateForm().then(f=>{
            if(f.isValid){
                this.loading = true;
                indexApis.saveOrUpdateTemplate({sourcetype:this.sourcetype,customid:this.customid,...this.form.getFormParams()}).then(action(({status, errorCode, error})=>{
                    if (status == '1') {
                        message.success(getLabel(18758,"保存成功"));
                        this.getTemplateListDataKey({customid:this.customid,sourcetype:this.sourcetype});
                        this.visible=false;
                    } else {
                        message.error(`[${getLabel(127353,"错误")+errorCode}]:${error}`);
                    }
                    this.loading = false;
                }));
            }else{
              f.showErrors();
            }
        });
    }

    @action
    edit=(id,templatename='',templatetype='',displayorder=0,isdefault=0)=>{
        this.form.resetForm();
        this.form.updateFields({id,templatename,templatetype,displayorder,isdefault}, true);
        this.visible=true;
    }

    @action
    handleTableChange=(pagination)=>{
        this.pagination=pagination;
        this.getTemplateListData();
    }


    @action
    delete=(id)=>{
        const mythis = this;
        Modal.confirm({
            title: getLabel(129890, '确定要删除吗?', 'label'),
            okText:getLabel(382958, '确定'),
            okType: 'danger',
            cancelText: getLabel(201,"取消"),
            onOk() {
                mythis.loading = true;
                indexApis.deleteTemplate({id}).then(action(({status, errorCode, error})=>{
                    if (status == '1') {
                        message.success(getLabel(20461,"删除成功"));
                        mythis.getTemplateListCount();
                        mythis.visible=false;
                    } else {
                        message.error(`[${getLabel(127353,"错误")+errorCode}]:${error}`);
                    }
                    mythis.loading = false;
                }));
            }
        });
    }

    @action
    setDefault=(id)=>{
        this.loading = true;
        indexApis.setDefault({sourcetype:this.sourcetype,customid:this.customid,id}).then(action(({status, errorCode, error})=>{
            if (status == '1') {
                message.success(getLabel(83885,"操作成功！"));
                this.getTemplateListData();
            } else {
                message.error(`[${getLabel(127353,"错误")+errorCode}]:${error}`);
            }
            this.loading = false;
        }));
    }

    @action
    setTemplateCustomCondition=(id)=>{
        this.id=id;
        this.visible_set_condition=true;
        this.loading = true;
        indexApis.getTemplateInfo({sourcetype:this.sourcetype,customid:this.customid,templateid:id,from:'templatemanage'}).then(action(({status, errorCode, error,conditionInfo,dataSource})=>{
            if (status == '1') {
                conditionInfo[0].items=conditionInfo[0].items.filter(item=>{
                    if(item.domkey[0]=='thisdate'||item.domkey[0]=='thisorg'){
                        return false;
                    }else{
                        return true;
                    }
                });
                this.conditionForm = new WeaForm();
                this.conditionInfo=conditionInfo;
                this.conditionForm.initFormFields(conditionInfo);

                let otherData={};
                for (let field in dataSource) {
                    if (this.conditionForm.has(field)) {
                        if(Array.isArray(dataSource[field])){
                            const _field = this.conditionForm.select(field)
                            _field.set(dataSource[field]);
                        }else{
                            otherData[field]=dataSource[field];
                        }
                    }
                }
                this.conditionForm.updateFields(otherData,false);

            } else {
                message.error(`[${getLabel(127353,"错误")+errorCode}]:${error}`);
            }
            this.loading = false;
        }));
    }

    @action
    setTemplateColumn=(id)=>{
        this.id=id;
        this.visible_set=true;
        this.loading = true;
        indexApis.getColumnSetInfo({sourcetype:this.sourcetype,customid:this.customid,id}).then(action(({status, errorCode, error,info})=>{
            if (status == '1') {
                this.DatasSet=info;
            } else {
                message.error(`[${getLabel(127353,"错误")+errorCode}]:${error}`);
            }
            this.loading = false;
        }));
    }

    @action
    saveTemplateField=()=>{
        this.visible_set=true;
        this.loading = true;
        indexApis.saveTemplateField({valuearray:JSON.stringify(this.DatasSet),id:this.id}).then(action(({status, errorCode, error})=>{
            if (status == '1') {
                message.success(getLabel(18758,"保存成功"));
                this.visible_set=false;
            } else {
                message.error(`[${getLabel(127353,"错误")+errorCode}]:${error}`);
            }
            this.loading = false;
        }));
    }

    @action
    saveCustomCondition=()=>{
        const getValues = (conditionInfo, values) => {
            let vi = toJS(values);
            let ci = toJS(conditionInfo[0].items);
            let rs = ci.map(c => `${c.domkey}`)
            let vs = rs.map(c => `${vi[c]}`);
            return JSON.stringify({ rs, vs });
        };
        indexApis.saveTemplate({
            action: "save",
            customid: this.customid,
            templateid: this.id,
            sourcetype: this.sourcetype,
            values: getValues( this.conditionInfo, this.conditionForm.values())
        }).then(({ status, error, ...props }) => {
            if (status == '1') {
                message.success(getLabel(18758, "保存成功。"));
            } else {
                message.error(error)
                throw error;
            }
        })
    }

    @action
    checkAll=(v)=>{
        this.DatasSet=this.DatasSet.map(item=>{
            item.isshow=v;
            return item;
        });
    }

    @action
    getIconInfo = (customid) => {
        indexApis.getAppInfoByID({ customid }).then((data: any) => {
            if (data.status == "1") {
                this.iconInfo = {
                    icon: data.icon || "icon-coms-ModelingEngine",
                    iconColor: data.iconColor || "#fff",
                    iconBg: data.iconBg || "#96358a"
                };
            }
        })
    }

}
